package com.saxon.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class cookieDemo extends HttpServlet {
    @Override
    protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding ("utf-8");
        resp.setContentType ("text/html;charset=UTF-8");
        resp.setCharacterEncoding ("utf-8");
        Cookie[] cookies = req.getCookies ();
        PrintWriter out = resp.getWriter ();
        if (cookies!=null){
            for (Cookie cookie : cookies) {
                String name = cookie.getName ();
                if (name.equals ("saxon")) {
                    String value = cookie.getValue ();
                    Date date = new Date (Long.parseLong (value));
                    out.print ("你上次来的时间是" + date);
                }
            }
        }else {
            out.write ("欢迎光临\n");
        }
        Cookie cookie = new Cookie ("saxon", System.currentTimeMillis () + "");
        cookie.setMaxAge (24*60*60);//Set-Cookie: saxon=1595912818749; Max-Age=86400; Expires=Wed, 29-Jul-2020 05:06:58 GMT
        resp.addCookie (cookie);//每次都给一个新的cookie,覆盖上一个同名cookie
    }

    @Override
    protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet (req, resp);
    }
}
